package com.wys.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayOpenAuthTokenAppModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.wys.pay.alipay.entity.AlipayConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AlipayCore {


    private static final Logger logger = LoggerFactory.getLogger(AlipayCore.class);

    private AlipayConfig alipayConfig;

    private AlipayClient alipayClient;

    public AlipayCore(AlipayConfig alipayConfig) throws AlipayApiException {
        this.alipayConfig = alipayConfig;
        alipayClient = initAliPayConfig(alipayConfig).getAliPayClient();
        //加入缓存
        AliPayApiConfigKit.putApiConfig(initAliPayConfig(alipayConfig));
    }

    public static AliPayApiConfig initAliPayConfig(AlipayConfig alipayConfig) throws AlipayApiException {
        Assert.isNull(alipayConfig, "初始化失败支付宝配置为null");
        AliPayApiConfig aliPayApiConf = AliPayApiConfig.builder().setAppId(alipayConfig.getAppId())
                .setAliPayCertContent(alipayConfig.getAliPayCertPath())
                .setCertModel(StringUtils.isNoneBlank(alipayConfig.getAliPayRootCertPath()))
                .setPrivateKey(alipayConfig.getPrivateKey())
                .setAliPayPublicKey(alipayConfig.getPublicKey())
                .setAliPayRootCertContent(alipayConfig.getAliPayRootCertPath())
                .setAliPayCertPath(alipayConfig.getAliPayCertPath())
                .setAliPayRootCertPath(alipayConfig.getAliPayRootCertPath())
                .setServiceUrl(alipayConfig.getServerUrl())
                .build();

        return StringUtils.isNoneBlank(aliPayApiConf.getAliPayCertContent(), aliPayApiConf.getAliPayRootCertContent(), aliPayApiConf.getAliPayRootCertPath(), aliPayApiConf.getAliPayCertPath()) ? aliPayApiConf.buildByCertContent() : aliPayApiConf.buildByCert();
    }


    /**
     * 获取应用授权auth token
     *
     * @param httpServletResponse
     * @param url                 alipay支付网关
     * @param isProd              是否为线上环境
     * @param appid               appId
     * @param redirectUri         回调url与支付宝配置的回调url一致
     * @throws IOException
     */
    public void authAppToken(HttpServletResponse httpServletResponse, String url, boolean isProd, String appid, String redirectUri) {
        try {
            if (StringUtils.isBlank(url)) {
                url = isProd ? AliPayApi.getOauth2Url(appid, redirectUri) : "https://openauth.alipaydev.com/oauth2/appToAppAuth.htm?app_id=" + appid + "&redirect_uri=" + redirectUri;
            }
            httpServletResponse.sendRedirect(url);
        } catch (IOException i) {
            logger.error("获取应该授权token失败:", i);
        }
    }

    public void authAppTokenFromSandbox(HttpServletResponse httpServletResponse, String appId, String redirectUrl) {
        authAppToken(httpServletResponse, null, false, appId, redirectUrl);
    }

    public void authAppTokenFromProd(HttpServletResponse httpServletResponse, String appId, String redirectUrl) {
        authAppToken(httpServletResponse, null, true, appId, redirectUrl);
    }


    /**
     * 支付回调url
     *
     * @param alipayClient
     * @param appid
     * @param appAuthCode
     * @return
     * @throws AlipayApiException
     */
    public String redirectUri(String appid, String appAuthCode) throws AlipayApiException {

        AlipayOpenAuthTokenAppModel model = new AlipayOpenAuthTokenAppModel();
        model.setGrantType("authorization_code");
        //585653e741a94237bbac33173c1f5A00
        model.setCode(appAuthCode);
        //authtoken 202209BB17a313bc9e5546dbb21d6a842719cX00
        return AliPayApi.openAuthTokenAppToResponse(alipayClient, false, model).getBody();
    }


    /**
     * 手机网站支付(h5)
     * @param httpServletResponse
     * @param alipayTradeWapPayModel
     * @param returnUrl 同步返回url
     * @param notifyUrl 异步通知url
     * @param isLog 是否打印日志
     * @throws AlipayApiException
     * @throws IOException
     */
    public void wapPay(HttpServletResponse httpServletResponse, AlipayTradeWapPayModel alipayTradeWapPayModel, String returnUrl, String notifyUrl, boolean isLog) throws AlipayApiException, IOException {
        AliPayApi.wapPay(httpServletResponse, alipayTradeWapPayModel, returnUrl, notifyUrl);
        if(isLog){
           logger.info("========================================打印支付信息:{}======================", httpServletResponse.getLocale().toString());
        }
    }

    //todo 退款、资金冻结 等业务待后续开发 目前仅作支付


}
